package com.henghai.zhenxuan.pay.alipay;

import static com.blankj.utilcode.util.StringUtils.getString;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.henghai.zhenxuan.R;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.pay.IPayManager;
import com.henghai.zhenxuan.pay.OnSuccessAndErrorListener;
import com.henghai.zhenxuan.pay.newpay.AuthResult;
import com.henghai.zhenxuan.pay.newpay.PayResult;

import java.util.Map;


public class AliPayTool implements IPayManager {


    public static AliPayTool getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final AliPayTool INSTANCE = new AliPayTool();
    }

    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_AUTH_FLAG = 2;
    private static OnSuccessAndErrorListener sOnSuccessAndErrorListener;
    @SuppressLint("HandlerLeak")
    private static Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        sOnSuccessAndErrorListener.onSuccess("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        sOnSuccessAndErrorListener.onError(getString(R.string.pay_failed) + resultStatus);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        sOnSuccessAndErrorListener.onSuccess(getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        sOnSuccessAndErrorListener.onError(getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


    @Override
    public void pay(Activity context, String orderInfo, OnSuccessAndErrorListener onRxHttp1) {
        sOnSuccessAndErrorListener = onRxHttp1;
        if (TextUtils.isEmpty(Const.ALIPAY_APP_ID) || (TextUtils.isEmpty(Const.ALIPAY_RSA2_PRIVATE) && TextUtils.isEmpty(Const.ALIPAY_RSA_PRIVATE))) {
            onRxHttp1.onError(getString(R.string.error_missing_appid_rsa_private));
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
//        boolean rsa2 = (Const.ALIPAY_RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Const.ALIPAY_APP_ID, rsa2, new PayModel(TimeUtils.getNowString(), "0.0.1", "茶品", "茶品"));
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? Const.ALIPAY_RSA2_PRIVATE : Const.ALIPAY_RSA_PRIVATE;
//        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        final String orderInfo1 = orderParam + "&" + sign;


        final Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(context);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Log.i("msp", result.toString());

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
